<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

/**
 * 直通车报表数据API
 */

class RptDemographicModel extends RptBaseModel {

	protected $tableName = 'rpt_demographic';
	/** @var object */
	private $me = null;
	/** @var object */
	private $subwayToken = null;

	/**
	 * 初始化。主要检查session['me']。
	 *
	 */
	public function _initialize() {
		parent :: _initialize();
		$this->me = session('me');
	}

	/**
	 * 同步某用户的给定$campaign_id的所有Demographic报表
	 * 
	 * @param int $user_id
	 * @param int campaign_id
	 * @return void
	 */
	public function syncDemographicReport($user_id , $campaign_id = 0) {
		if(empty($user_id)) {
			throw_exception('参数错误: $user_id必须>0. ');
		}
		if($campaign_id <= 0) {
			throw_exception('参数错误: 目前只支持$campaign_id>0的情况. ');
		}
		
		$entity = 'rpt-campaign-demographic:' . $campaign_id;
		$updated = SyncModel::getLatestUpdated($user_id , $entity);
// 		$startTime = $updated ? date("Y-m-d",strtotime( $updated ) + 24*3600) : date("Y-m-d",strtotime( $updated ) - 90*24*3600);
// 		$endTime = date("Y-m-d",time() - 24*3600);
		$time_slot = SyncModel::getSyncTimeSlot($user_id, $entity);
		if($time_slot){
			$rptMdl = new RptModel();
			$rptMdl->syncSummaryData($user_id, 'rpt_demographic', 
					$campaign_id ,0, $time_slot['start'] , $time_slot['end']);
		} else {
			return false;
		}
		$condition = array(
					'taobao_user_id' => $user_id,
					'campaign_id' => $campaign_id
				);
		$updated = $this->where($condition)->order('date DESC')->getField('date');
		if($updated) {
			SyncModel::setLatestUpdated( $user_id , $entity , $updated);
		}
		return true;
	}
	
}